package com.zk.tools.schdule;

import com.alibaba.fastjson.JSONObject;
import com.zk.tools.contants.Contants;
import com.zk.tools.model.EmailConfJsonMO;
import com.zk.tools.util.MailSenderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

@Component
public class ReLoadConf {

    private static final Logger logger = LoggerFactory.getLogger(ReLoadConf.class);

    @Scheduled(cron = Contants.RELOADCONF_CRON)
    public void initConf() {
        JSONObject jsonObject = JSONObject.parseObject(readJsonFile());
        EmailConfJsonMO emailConfJson = jsonObject.toJavaObject(EmailConfJsonMO.class);
        MailSenderUtil.registerJavaMailSenderIMAP(emailConfJson);
        logger.info("initConf #######");
    }


    public String readJsonFile() {
        StringBuffer sb = new StringBuffer();
        File jsonFile = new File(Contants.confPath);
        try (
                Reader reader = new InputStreamReader(new FileInputStream(jsonFile))
        ) {
            int ch = 0;
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sb.toString();
    }
}
